package com.hinotoyk.testsystem.controller;

import com.hinotoyk.testsystem.entity.*;
import com.hinotoyk.testsystem.service.QuestionService;
import com.hinotoyk.testsystem.service.StudentAnswerService;
import com.hinotoyk.testsystem.service.TeacherService;
import com.hinotoyk.testsystem.service.TestPaperService;
import com.hinotoyk.testsystem.uitls.*;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.List;

@Controller
public class TestPaperController {
    private static ChainRandom r = new ChainRandom();

    @Resource
    private TestPaperService serivice;

    @Resource
    private QuestionService questionService;

    @Resource
    private StudentAnswerService answerService;

    @Resource
    private TeacherService teacherService;

    @RequestMapping("/teacher/testpaper/createpage")
    public String GenPage(Model model, HttpServletRequest request){
        return "teacher/testpaper/createpage";
    }

    @RequestMapping("/teacher/testpaper/showpage/{id}")
    public String ShowPage(@PathVariable(value = "id") int id, Model model, HttpServletRequest request){

        TestPaperInfo tp = serivice.FindTestPaper(id);
        if(tp != null) {
            model.addAttribute("tp", tp);
            TestPagerJson obj = TestPagerJson.MakeByJSONString(tp.getTestPaperDetail());
            TestPaperAddSave(obj);
            model.addAttribute("json", obj);
            model.addAttribute("save", obj.getSave());
        }
        return "teacher/testpaper/showpage";
    }

    @RequestMapping("/teacher/testpaper/create")
    public String CreateTestPaper(Model model, HttpServletRequest request){
        Teacher t = (Teacher)request.getSession().getAttribute("teacher");
        int teacherId = 1;
        if(t != null)
            teacherId = t.getTeacherId();

        boolean flag = false;

        TestPaperInfo tp = new TestPaperInfo();
        tp.setCourseId(0);
        tp.setTeacherId(teacherId);
        tp.setTestPaperName(request.getParameter("name"));

        TestPagerJson json = new TestPagerJson();
        int difficult = Integer.valueOf(request.getParameter("difficult"));
        String stime = request.getParameter("startTime");
        int ttime = Integer.valueOf(request.getParameter("testTime"));

        GenQuestion(json, QuestionType.SGQuestion.getType(), difficult, Integer.valueOf(request.getParameter("sgnums")));
        GenQuestion(json, QuestionType.PLQuestion.getType(), difficult, Integer.valueOf(request.getParameter("plnums")));
        GenQuestion(json, QuestionType.FillingQuestion.getType(), difficult, Integer.valueOf(request.getParameter("fillnums")));
        GenQuestion(json, QuestionType.TOFQuestion.getType(), difficult, Integer.valueOf(request.getParameter("tofnums")));
        GenQuestion(json, QuestionType.EssayQuestion.getType(), difficult, Integer.valueOf(request.getParameter("essaynums")));

        json.setStartTime(stime);
        json.setTestTime(ttime);

        json.setSgScore(Integer.valueOf(request.getParameter("sgscore")));
        json.setPlScore(Integer.valueOf(request.getParameter("plscore")));
        json.setEssayScore(Integer.valueOf(request.getParameter("essayscore")));
        json.setFillScore(Integer.valueOf(request.getParameter("fillscore")));
        json.setTofScore(Integer.valueOf(request.getParameter("tofscore")));
        json.ReCalculateTotalScore();

        System.out.println(json.toString());

        tp.setTestPaperDetail(json.toString());
        System.out.println("-------------------+-");

        flag = serivice.AddTestPaper(tp);
        System.out.println(tp.getTestPaperId());
        System.out.println("----------------------");

        List<Student> studentList = teacherService.getStudentByTeachId(teacherId);
        for(int i=0;i<studentList.size();i++){
            answerService.insertStuAnwersInfo(studentList.get(i).getStudentId(),tp.getTestPaperId());
        }

        model.addAttribute("title", "生成题目");
        model.addAttribute("status", (flag)?"成功":"失败");
        return "/teacher/statuspage";
    }

    @RequestMapping("/teacher/testpaper/delete/{id}")
    public String DeleteTestPaper(@PathVariable(value = "id") int id, Model model, HttpServletRequest request){
        boolean flag = false;

        flag = serivice.DeleteTestPaper(id);

        model.addAttribute("title", "生成题目");
        model.addAttribute("status", (flag)?"成功":"失败");
        return "/teacher/statuspage";
    }


    @RequestMapping("/student/testpaper/historypage/{tid}/{sid}")
    public String StuHistoryPage(@PathVariable(value = "tid") int tid, @PathVariable(value = "sid") int sid, Model model){
        TestPaperInfo tp = serivice.FindTestPaper(tid);
        StuAnswersInfo sai = answerService.FindStuAnswersInfoById(tid, sid);
        System.out.println(sai);
        if(tp != null && sai != null && sai.getStatus() != 0) {
            model.addAttribute("tp", tp);
            TestPagerJson obj = TestPagerJson.MakeByJSONString(tp.getTestPaperDetail());
            TestPaperAddSave(obj);
            model.addAttribute("json", obj);
            model.addAttribute("save", obj.getSave());

            StudentAnswerJson obj2 = StudentAnswerJson.MakeByJSONString(sai.getAnswerDetail());

            model.addAttribute("answerJson", obj2);
        }
        return "/student/testpaper/historypage";
    }

    @RequestMapping("/student/testpaper/showpage/{id}")
    public String ShowStuPage(@PathVariable(value = "id") int id, Model model){
        TestPaperInfo tp = serivice.FindTestPaper(id);
        if(tp != null) {
            model.addAttribute("tp", tp);
            TestPagerJson obj = TestPagerJson.RandomByJSONString(tp.getTestPaperDetail());
            TestPaperAddSave(obj);

            // 可以使用 TimeTool 比较 时间
            if(TimeTool.GetLongTime() < TimeTool.DateToLong(obj.getStartTime())){
                // 未到考试时间
                model.addAttribute("title", "考试出错");
                model.addAttribute("status", "未到考试时间，还不能考试");
                return "/teacher/statuspage";
            }

            model.addAttribute("json", obj);
            System.out.println(obj.toString());

            model.addAttribute("save", obj.getSave());
        }
        return "/student/testpaper/showpages";
    }

    @RequestMapping("/student/testpaper/answer")
    @ResponseBody
    public String GetAnswer(@RequestBody String answerurl, HttpServletRequest request) throws UnsupportedEncodingException {
        answerurl = URLDecoder.decode(answerurl,"utf-8");
        System.out.println(answerurl);
        QueryMap map = QueryMap.parse(answerurl);
        System.out.println(map.toString());
        int testPaperId = Integer.valueOf(map.getParameter("testPaperId"));

        TestPaperInfo tinfo = serivice.FindTestPaper(testPaperId);
        TestPagerJson testJson = TestPagerJson.MakeByJSONString(tinfo.getTestPaperDetail());
        TestPaperAddSave(testJson);

        StudentAnswerJson answerJson = StudentAnswerJson.MakeAndGetScore(testJson, map);

        int studentId = 1;
        Student s = (Student)request.getSession().getAttribute("student");
        if(s != null)
            studentId = s.getStudentId();

        StuAnswersInfo sinfo = answerService.FindStuAnswersInfoById(testPaperId, studentId);
        System.out.println(sinfo.toString());
        sinfo.setAnswerDetail(answerJson.toString());
        sinfo.setScore(answerJson.getTofScore());
        sinfo.setStatus(1);
        sinfo.setTestPaperId(testPaperId);
        sinfo.setStudentId(studentId);
        System.out.println(sinfo.toString());

        if(!answerService.UpdateStuAnswersInfo(sinfo))
            return "false";

        return "success";
    }

    @RequestMapping("/teacher/testpaper/getAllTest")
    public String getAllTest(Model model,int teacherId){
        List<TestPaperInfo> list = serivice.getAllTestPaperByTeachId(teacherId);
        System.out.println(list);
        model.addAttribute("teacherList",list);
        return "/teacher/testpaper/allTestPage";
    }




    public void GenQuestion(TestPagerJson json, int type, int difficult, int nums){
        if(type == QuestionType.SGQuestion.getType()){
            List<SGQuestion> list = questionService.FindSGQuestionByDifficult(difficult);
            if(list != null) {
                r.setChain(list.size());
                for (int i = 0; i < nums; ++i)
                    json.addSGQuestion(list.get(r.nextInt()).getSgQuestionId());
            }
        }else if(type == QuestionType.FillingQuestion.getType()){
            List<FillingQuestion> list = questionService.FindFillQuestionByDifficult(difficult);
            if(list != null) {
                r.setChain(list.size());
                for (int i = 0; i < nums; ++i)
                    json.addFillingQuestion(list.get(r.nextInt()).getFillQuestionId());
            }
        }else if(type == QuestionType.EssayQuestion.getType()){
            List<EssayQuestion> list = questionService.FindEssayQuestionByDifficult(difficult);
            if(list != null) {
                r.setChain(list.size());
                for (int i = 0; i < nums; ++i)
                    json.addEssayQuestion(list.get(r.nextInt()).getEssayQuestionId());
            }
        }else if(type == QuestionType.PLQuestion.getType()){
            List<PLQuestion> list = questionService.FindPLQuestionByDifficult(difficult);
            if(list != null) {
                r.setChain(list.size());
                for (int i = 0; i < nums; ++i)
                    json.addPLQuestion(list.get(r.nextInt()).getPlQuestionId());
            }
        }else if(type == QuestionType.TOFQuestion.getType()){
            List<TOFQuestion> list = questionService.FindTOFQuestionByDifficult(difficult);
            if(list != null) {
                r.setChain(list.size());
                for (int i = 0; i < nums; ++i)
                    json.addTOFQuestion(list.get(r.nextInt()).getTofQuestionId());
            }
        }
    }

    public void TestPaperAddSave(TestPagerJson json){
        TestPaperSaveAddQuestion(json.getSave(), QuestionType.SGQuestion.getType(), json.getSgList());
        TestPaperSaveAddQuestion(json.getSave(), QuestionType.PLQuestion.getType(), json.getPlList());
        TestPaperSaveAddQuestion(json.getSave(), QuestionType.FillingQuestion.getType(), json.getFillList());
        TestPaperSaveAddQuestion(json.getSave(), QuestionType.TOFQuestion.getType(), json.getTofList());
        TestPaperSaveAddQuestion(json.getSave(), QuestionType.EssayQuestion.getType(), json.getEssayList());
    }

    public void TestPaperSaveAddQuestion(TestPaperSave save, int type, List<Integer> idList){
        if(idList == null) return;

        for(int i = 0; i < idList.size(); ++i)
            if(type == QuestionType.SGQuestion.getType()){
                save.getSgList().add(questionService.FindSGQuestion(idList.get(i)));
            }else if(type == QuestionType.FillingQuestion.getType()){
                save.getFillList().add(questionService.FindFillingQuestion(idList.get(i)));
            }else if(type == QuestionType.EssayQuestion.getType()){
                save.getEssayList().add(questionService.FindEssayQuestion(idList.get(i)));
            }else if(type == QuestionType.PLQuestion.getType()){
                save.getPlList().add(questionService.FindPLQuestion(idList.get(i)));
            }else if(type == QuestionType.TOFQuestion.getType()){
                save.getTofList().add(questionService.FindTOFQuestion(idList.get(i)));
            }
    }

    public int TestPaperScore(TestPagerJson test, StudentAnswerJson answer){
        int score = 0;

        return score;
    }
}
